﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
using AutoMapper;
using Mehdime.Entity;
using WikeSoft.Core;
using WikeSoft.Core.Extension;
using WikeSoft.Data;
using WikeSoft.Data.Models.Sys;
using WikeSoft.Enterprise.Entities;
using WikeSoft.Enterprise.Interfaces.Sys;
using WikeSoft.Enterprise.Models.Filters.Sys;

namespace WikeSoft.Enterprise.AppServices.Sys
{
    /// <summary>
    /// 角色服务
    /// </summary>
    public class KeyValueService : IKeyValueService
    {
        private readonly IMapper _mapper;
        private readonly IDbContextScopeFactory _dbContextScopeFactory;
        private ObjectCache _cache;
        private const string Config = "wikesoft.keyvalueConifg";
        public KeyValueService(IMapper mapper, IDbContextScopeFactory dbContextScopeFactory)
        {
            _mapper = mapper;
            _dbContextScopeFactory = dbContextScopeFactory;
            _cache = MemoryCache.Default;
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool Add(KeyValueAddModel model)
        {
            using (var scope = _dbContextScopeFactory.Create())
            {

                var db = scope.DbContexts.Get<WikeDbContext>();
                var entity = _mapper.Map<KeyValueAddModel, SysKeyValue>(model);

                db.SysKeyValues.Add(entity);

                scope.SaveChanges();

                _cache.Remove(Config);
            }
            return true;
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool Edit(KeyValueEditModel model)
        {
            using (var scope = _dbContextScopeFactory.Create())
            {
                var db = scope.DbContexts.Get<WikeDbContext>();
                var userEntity = db.SysKeyValues.Load(model.Id);
                _mapper.Map(model, userEntity);

                scope.SaveChanges();
                _cache.Remove(Config);
            }
            return true;
        }

        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        public KeyValueEditModel Find(Guid id)
        {
            using (var scope = _dbContextScopeFactory.CreateReadOnly())
            {
                var db = scope.DbContexts.Get<WikeDbContext>();
                var entity = db.SysKeyValues.Load(id);
                return _mapper.Map<SysKeyValue, KeyValueEditModel>(entity);
            }
        }




        /// <summary>
        /// 分页查询信息
        /// </summary>
        /// <param name="filters"></param>
        /// <returns></returns>
        public PagedResult<KeyValueModel> Query(KeyValueFilter filters)
        {
            using (var scope = _dbContextScopeFactory.CreateReadOnly())
            {
                var db = scope.DbContexts.Get<WikeDbContext>();
                var query = db.SysKeyValues.Where(x => true);
                if (filters.keywords.IsNotBlank())
                {
                    query = query.Where(x => x.Key.Contains(filters.keywords) || x.CnName.Contains(filters.keywords) || x.Value.Contains(filters.keywords));
                }

                var data = query.OrderByCustom(filters.sidx, filters.sord)
                    .Select(item => new KeyValueModel
                    {
                        Id = item.Id,
                        CnName = item.CnName,
                        Key = item.Key,
                        Value = item.Value,
                        Memo = item.Memo,
                        //TrueNames = string.Join(";", item.SysUsers.AsEnumerable().Select(p => p.TrueName).ToArray())
                    }).Paging(filters.page, filters.rows);



                return data;
            }
        }

        public List<KeyValueModel> GetAll()
        {
            List<KeyValueModel> cache = _cache.Get(Config) as List<KeyValueModel>;

            if (cache != null)
            {
                return cache;
            }
            using (var scope = _dbContextScopeFactory.CreateReadOnly())
            {
                var db = scope.DbContexts.Get<WikeDbContext>();
                var query = db.SysKeyValues.Where(x => true);
                var data = query.Select(item => new KeyValueModel
                    {
                        Id = item.Id,
                        CnName = item.CnName,
                        Key = item.Key,
                        Value = item.Value,
                        Memo = item.Memo,

                    }).ToList();

                cache = data;
                _cache.Add(Config, cache, ObjectCache.InfiniteAbsoluteExpiration);

                return data;
            }
        }

        public string GetValue(string key)
        {
            List<KeyValueModel> datas = GetAll();

            var firstOrDefault = datas.FirstOrDefault(x => x.Key == key);
            if (firstOrDefault != null)
                return firstOrDefault.Value;

            return string.Empty;
        }
    }
}
